package com.atguigu.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;
    /**
     * 使用Json序列化机制进行消息转换
     * @return
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制rabbitTemplate
     * 1、spring.rabbitmq.publisher-confirms=true
     * 2、设置确认回调
     */
    @PostConstruct //MyRabbitConfig对象创建完成之后执行这个方法
    public void initRabbitTemplate(){
        //设置确认回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *  只要消息抵达服务器  ack就为true
             * @param correlationData 当前消息的唯一关联数据（这个是消息唯一的Id）
             * @param ack               消息是否成功收到
             * @param cause             失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("correlationData:  "+correlationData);
                System.out.println("ack:   "+ack);
                System.out.println("cause:   "+cause);
            }
        });

        //设置消息抵达队列的确认回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 只要消息投递给指定的队列失败就会触发这个
             * @param message 投递失败消息的详细内容
             * @param replyCode 回复的状态码
             * @param replyText 回复的文本
             * @param exchange 哪个交换机
             * @param routingKey 哪个路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("message:  "+message);
                System.out.println("replyCode:  "+replyCode);
                System.out.println("replyText:  "+replyText);
                System.out.println("exchange:  "+exchange);
                System.out.println("routingKey:  "+routingKey);
            }
        });
    }
}
